﻿using System;
using System.Diagnostics;
using System.Timers;

namespace Sustainalytics.ReportGenerator.BL
{
    public class TTLManager
    {
        private readonly Timer _timer;
        private readonly double _timeToLive;

        public TTLManager(double timeToLive)
        {
            _timer = new Timer(timeToLive);
            _timeToLive = timeToLive;
        }

        public static void Shutdown()
        {
            PdfGenerationSerilog.Log.Info("System shutdown");

            if (!Environment.UserInteractive)
            {
                Process.Start("shutdown", "/s /t " + "50");
            }
        }

        public void Start()
        {
            PdfGenerationSerilog.Log.Info(
                string.Format(
                    "PDF Generation shutdown scheduled at {0}",
                    DateTime.UtcNow.Add(TimeSpan.FromMilliseconds(_timeToLive))));

            _timer.Elapsed += OnTTLElapsed;
            _timer.Start();
        }

        private static void OnTTLElapsed(object sender, ElapsedEventArgs args)
        {
            Shutdown();
        }
    }
}
